package offer.zixing.chapter12;

import java.util.Random;

public class Test76_1 {

    public static void main(String[] args) {
        int[] arr = {7, 3, 2, 8, 1, 9, 5, 4, 6};
        sort(arr, 0, arr.length - 1);
        print(arr);
    }

    public static void sort(int[] arr, int leftBound, int rightBound) {
        if (leftBound >= rightBound) {
            return;
        }
        partition(arr, leftBound, rightBound);
    }

    static void partition(int[] arr, int leftBound, int rightBound) {

//        int random = new Random().nextInt(rightBound - leftBound + 1);
        int pivot = arr[rightBound];
        int left = leftBound;
        int right = rightBound - 1;
        while (left < right) {
            while (arr[left] <= pivot) {
                left++;
            }
            while (arr[right] >= pivot) {
                right--;
            }
            if (left < right) {
                swap(arr, left, right);
            }
        }
    }

    static void swap(int[] arr, int i, int j) {
        if (arr[i] != arr[j]) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }

    static void print(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}
